const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const configLoader = require('./utils/config-loader');
const logger = require('./utils/logger');
const webhookRouter = require('./webhook/webhook');
const fileManager = require('./storage/file-manager');
const PluginManager = require('./core/plugin-manager');
const MessageSender = require('./lib/message-sender');

class App {
    constructor() {
        this.app = express();
        this.pluginManager = null;
        this.messageSender = null;
        this.init();
    }

    async init() {
        try {
            // 加载配置
            this.config = await configLoader.load();
            
            // 初始化消息发送器
            this.messageSender = new MessageSender(this.config);
            await this.messageSender.initialize();

            // 初始化插件管理器
            this.pluginManager = new PluginManager(this.config);
            this.pluginManager.setMessageSender(this.messageSender);
            await this.pluginManager.autoLoadPlugins();

            // 初始化中间件
            this.setupMiddleware();
            
            // 初始化存储
            await this.setupStorage();
            
            // 初始化路由（传递插件管理器）
            this.setupRoutes();
            
            // 启动服务器
            this.startServer();
        } catch (error) {
            console.error('❌ 应用初始化失败:', error);
            process.exit(1);
        }
    }

    setupMiddleware() {
        this.app.use(cors());
        this.app.use(bodyParser.json({ limit: '10mb' }));
        this.app.use(bodyParser.urlencoded({ extended: true }));
        this.app.use(express.static('public'));
    }

    async setupStorage() {
        try {
            await fileManager.initializeStorage();
            console.log('✅ 存储系统初始化完成');
        } catch (error) {
            console.error('❌ 存储系统初始化失败:', error);
        }
    }

    setupRoutes() {
        // 传递插件管理器给webhook路由
        this.app.use(this.config.webhook.path, webhookRouter(this.pluginManager));
        
        // 管理接口
        this.app.get('/health', (req, res) => {
            res.json({ 
                status: 'ok', 
                timestamp: new Date().toISOString(),
                service: 'napcat-webhook',
                plugins: this.pluginManager ? this.pluginManager.getStats() : 'initializing'
            });
        });

        this.app.get('/plugins', (req, res) => {
            if (!this.pluginManager) {
                return res.status(503).json({ error: '插件管理器未初始化' });
            }
            res.json({
                status: 'success',
                data: this.pluginManager.getAllPluginsInfo()
            });
        });

        this.app.get('/help', (req, res) => {
            if (!this.pluginManager) {
                return res.status(503).json({ error: '插件管理器未初始化' });
            }
            res.json({
                status: 'success',
                data: this.pluginManager.getGlobalHelp()
            });
        });

        // 主页
        this.app.get('/', (req, res) => {
            res.send(`
                <html>
                    <head><title>NapCat Webhook</title></head>
                    <body>
                        <h1>NapCat Webhook 接收端运行中</h1>
                        <p>Webhook 路径: ${this.config.webhook.path}</p>
                        <p>端口: ${this.config.server.port}</p>
                        <p>插件数量: ${this.pluginManager ? this.pluginManager.plugins.size : 0}</p>
                        <p><a href="/health">健康检查</a> | <a href="/plugins">插件列表</a> | <a href="/help">帮助</a></p>
                    </body>
                </html>
            `);
        });
    }

    startServer() {
        const port = this.config.server.port;
        const host = this.config.server.host;
        
        this.app.listen(port, host, () => {
            console.log(`✅ NapCat Webhook 服务器启动成功`);
            console.log(`📍 服务地址: http://${host}:${port}`);
            console.log(`🔗 Webhook 路径: ${this.config.webhook.path}`);
            console.log(`🤖 NapCat 地址: ${this.config.napcat.baseUrl}`);
            console.log(`🔌 已加载插件: ${this.pluginManager ? this.pluginManager.enabledPlugins.size : 0}个`);
        });

        this.app.on('error', (error) => {
            console.error('❌ 服务器启动失败:', error);
            process.exit(1);
        });
    }
}

// 启动应用
new App();